<?php
//$sql=file_get_contents("moban.sql");
//$sql_row=explode(";\n",$sql);

////require 'includes/global.php';

//echo '<pre>';
//$t=file('../includes/global.php');
//print_r($sql_row);
//echo '</pre>';
//exit;


//error_reporting(E_ALL);
/***********************
*
* 简易安装系统
*
* 以下参数必须到global里设定好
*	$sitename:将要更新的字段名(就是web那个啦)
*	$dbusername:数据库名(这个一定要填对哦,要不然更新到别的库啦)
*
*********************/
if(is_file('core.txt') && file_get_contents('core.txt')=='Y'){
    die('您已经安装过,如果需要重新安装，请删除文件:core.txt');
}
if($_POST['mode']=='install'){
	//if($dbusername==''){
	  //echo 'Please set you username of DB.';
	  //exit;
	//}
	//if($sitename==''){
	  //echo 'Please set sitename.';
	  //exit;
	//}
	//if($dbname==''){
	  //echo 'Please select dbname.';
	  //exit;
	//}
	//if($tmpname==''){
	  //echo 'Node: You tmpname is empty.';
	  //exit;
	//}
	$_result['success']=true;
	$_result['msg']='ok';

	$host=$_POST['host'];
	$dbusername=$_POST['dbuser'];
	$dbpassword=$p=$_POST['password']!=''?','.$p:'';
	$dbname=$_POST['dbname'];
	$sitename=$_POST['sitename'];
	$tmpname=$_POST['tmpname'];





	$connect = @ mysql_connect($host,$dbusername.$dbpassword);
	if(!$connect){
		$_result['msg']="数据库链接不上\n请检查填写的数据库:地址、用户名、密码 是否正确!";
		$_result['id']="dbuser";
	}else{

		/*设置编码*/
		mysql_query("SET NAMES UTF8");

		/*数据库操作*/
		if(@ mysql_selectdb( $dbname, $connect )){	//判断数据库是否已存在
			$_result['msg']="数据库[{$dbname}]已存在,请将数据库删除,再进行安装!";
			$_result['id']="dbname";
		}else if(!@mysql_query("CREATE DATABASE {$dbname} DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci")){		//创建数据库
			$_result['msg']="数据库[{$dbname}]创建失败!";
			$_result['id']="dbname";
		}else if(!@ mysql_selectdb( $dbname, $connect )){	//选择数据库
			$_result['msg']="没有数据库[{$dbname}]";
			$_result['id']="dbname";
		}else{
			$sql=file_get_contents("moban.sql");
			$sql_row=explode(";\n",$sql);
			$error=false;
			foreach($sql_row as $sqlK=>$sqlV){
				if(!@ mysql_query($sqlV) && trim($sqlV)!=''){	//建表插入基本数据
					$error=true;
					break;
				}
			}
			if($error){	//建表插入基本数据
				$_result['msg']="初始数据插入失败!";
				$_result['id']="dbname";
			}else{
				$j=0;
				$tables = mysql_list_tables( $dbname );


				while ($row = mysql_fetch_row($tables)) {
					//print "Table: $row[0],\t\t\tupdate web of field had <b>success</b>!\n<br />";
					mysql_query("ALTER TABLE `{$row[0]}`  DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;");	//utf-8编码
					mysql_query("update `{$row[0]}` set web='{$sitename}' where 1");
				}

				//更新配置文件
				$t=@file('../includes/global.php');

				if(!@ file_put_contents('../includes/global.php',$t)){
					$_result['msg']="数据库更新完成,但配置文件打开失败,无法写入核心配置信息!请手动修改或重新安装！";
				}else{
					$t[8]="\$sitename='{$sitename}';\r\n";
					$t[15]="\$servername = '{$host}';		//数据库所在目录\r\n";
					$t[16]="\$dbusername = '{$dbusername}';	//数据库用户名\r\n";
					$t[17]="\$dbpassword = '{$dbpassword}';	//数据库密码\r\n";
					$t[18]="\$dbname		= '{$dbname}';		//数据库名称\r\n";
					$t[19]="\$tmpname='{$tmpname}/';//模版所在目录\r\n";

					if(!@ file_put_contents('../includes/global.php',$t)){
						$_result['msg']="数据库更新完成,但配置文件写入失败!";
					}
				}
				
				file_put_contents('core.txt',"Y");

			   //while( $line = mysql_fetch_row( $tables ) )
			   //{
				   //$fields = mysql_list_fields( $dbname, $line[0], $connect );
				   //$columns = mysql_num_fields( $fields );

				   //for ($i = 0; $i < $columns; $i++) {
						   //$nomField = mysql_field_name( $fields, $i );
					   //$sql = "SELECT ".$nomField." FROM " . $line[0] .
						   //" WHERE " .
							   //$nomField . " LIKE '%".$word."' LIMIT 1";

					   //$query = mysql_query( $sql );
					   //if( mysql_num_rows( $query ) > 0)
					   //{
						   //$result = mysql_fetch_array( $query );
						   //echo "Table: <b>".$line[0]."</b><br>";
						   //echo "Field: <b>".$nomField."</b><br>";
						   //echo "SQL: <b>".$sql."</b><br>";
						   //echo "Result: <b>" . str_replace( $word, "<font color='blue'>". $word . "</font>", $result[0] ) . "</b>";
						   //echo "<br><br>";
						   //$j++;
					   //}
				   //}
			   //}
			   //echo "<br><br><br>";
			   //echo "Results: All success!";
			}
	   }
	}
	   echo json_encode($_result);
	   exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>众盛科技-CMS-简易安装程序</title>

<link rel="stylesheet" type="text/css" href="/jimu/ext/resources/css/ext-all.css" />
<script type="text/javascript" src="/jimu/ext/adapter/jquery/jquery.js"></script>
<script type="text/javascript" src="/jimu/ext/adapter/jquery/ext-jquery-adapter.js"></script>
<script type="text/javascript" src="/jimu/ext/ext-all.js"></script>

<link rel="stylesheet" type="text/css" href="/css/main.css"/>
</head>
<body>
<script>
Ext.onReady(function(){
$("body").css({background:"#D6E2F2",color:"#fff"});
          //使用表单提示
          Ext.QuickTips.init();
          Ext.form.Field.prototype.msgTarget = 'side';

		  //定义表单
          var simple = new Ext.FormPanel({
                labelAlign: 'center',
				labelWidth: 105,
				baseCls: 'x-plain',
				defaults: {width: 150},
				monitorValid: true,
				margins:'13 0 0 0',
				defaultType: 'textfield',//默认字段类型

				//定义表单元素
				items: [{
						fieldLabel:"数据库地址",
						name:"host",
						id:"host",
						valueField:'abbr',
						readOnly:true,
						width:180,
						value:"localhost",
						emptyText:"请输入数据库地址",
						allowBlank:false,//不允许为空
						blankText:'数据库地址不能为空'//错误提示内容
					},{
						//style:'background:url(/admin/img/Fwdw_icons_57.png) no-repeat center left',
						fieldLabel: '数据库用户名',
						validateOnBlur:true,
						name: 'dbuser',//元素名称
						id:'dbuser',
						//anchor:'95%',//也可用此定义自适应宽度
						width:180,
						allowBlank:false,//不允许为空
						blankText:'数据库用户名不能为空'//错误提示内容
					},{
					    inputType:'password',
						fieldLabel: '数据库密码',
						//anchor:'95%',
						width:180,
						name: 'password',
						allowBlank:true
						//blankText:'密码不能为空'
					},{
						//style:'background:url(/admin/img/Fwdw_icons_57.png) no-repeat center left',
						fieldLabel: '数据库名称',
						name: 'dbname',//元素名称
						id:'dbname',
						//anchor:'95%',//也可用此定义自适应宽度
						width:180,
						allowBlank:false,//不允许为空
						blankText:'网站名称不能为空'//错误提示内容
					},{
						//style:'background:url(/admin/img/Fwdw_icons_57.png) no-repeat center left',
						fieldLabel: '网站名称',
						name: 'sitename',//元素名称
						id:'sitename',
						//anchor:'95%',//也可用此定义自适应宽度
						width:180,
						allowBlank:false,//不允许为空
						blankText:'网站名称不能为空'//错误提示内容
					},{
						//style:'background:url(/admin/img/Fwdw_icons_57.png) no-repeat center left',
						fieldLabel: '模版目录',
						name: 'tmpname',//元素名称
						id:'tmpname',
						//anchor:'95%',//也可用此定义自适应宽度
						width:180,
						allowBlank:false,//不允许为空
						blankText:'模版目录不能为空'//错误提示内容
					},{
					    inputType:'hidden',
						//fieldLabel: '密码',
						//anchor:'95%',
						name: 'mode',
						value:'install'
						//allowBlank:false,
						//blankText:'密码不能为空'
					}
				],

			    keys:[{ //处理键盘回车事件
			        key:Ext.EventObject.ENTER,
			        fn:onOK,
			        scope:this
			    }],

				buttons: [{
					text: '安装',
					id:	'loginSubmit',
					type: 'submit',

					//定义表单提交事件
					handler:function(){
                              if(simple.form.isValid()){//验证合法后使用加载进度条
							      Ext.MessageBox.show({
									   title: '请稍等',
									   msg: '正在安装...',
									   progressText: '',
									   width:300,
									   progress:true,
									   closable:false,
									   animEl: 'loding'
								   });
								   //控制进度速度
								   var f = function(v){
									 return function(){
												var i = v/11;
												Ext.MessageBox.updateProgress(i, '');
								            };
								   };

								   for(var i = 1; i < 13; i++){
										setTimeout(f(i), i*150);
								   }

								  //提交到服务器操作
								  simple.form.doAction('submit',{
									 url:'install.php',//文件路径
									 method:'post',//提交方法post或get
									 params:'{mode:install}',
									 //提交成功的回调函数
									 success:function(form,action){
											if (action.result.msg=='ok') {
												Ext.Msg.alert('安装完成','安装完成!请删除根目录下的install文件夹!');
												document.getElementById('loginSubmit').disabled=true;
												window.location="/admin";
											} else {
												Ext.Msg.alert('安装错误',action.result.msg);
												//Ext.get(action.result.id).select();
											}
									 },
									 //提交失败的回调函数
									 failure:function(){
											Ext.Msg.alert('错误','服务器出现错误请稍后再试！');
									 }
								  });
							   }
					},formBind:true
				},{
					text: '重置',
					handler:function(){simple.form.reset();}//重置表单
				},{
					text: '安装方法',
					handler:function(){
							var install=new Ext.Window({title:'安装方法',width:800,height:500,html:'<iframe style="border: 0px none ;width:100%;height:100%;background:#CAD9EC;" src="readme.txt" ></iframe>'});
							install.show();
					}
				}]
			});



		        	//确定按钮事件
			        function onOK() {
			            var but=document.getElementsByTagName("button");
						var butlen=but.length;
						for(i=0;i<butlen;i++){
							but[i].innerHTML=='安装'?but[i].click():'';
						}
			        }

				var log = new Ext.Panel({
					title: '更新LOG',
					region: 'east',
					split: true,
					width: 200,
					collapsible: true,
					closable:false,//禁止关闭
					//autoScroll :true,//自动显示滚动条
					plain: true,
					margins:'3 0 3 3',
					cmargins:'3 3 3 3',
					tools:[{
						id:'maximize ',
						qtip:'新窗口查看',
						handler:function () {
							var nl=new Ext.Window({title:'更新LOG',width:800,height:500,html:'<iframe style="white-space:normal;border: 0px none ;width:100%;height:100%;background:#CAD9EC;" src="/install/log.txt" ></iframe>'});
							nl.show();
						}
					}],
					html :'<iframe style="white-space:normal;border: 0px none ;width:100%;height:100%;background:#CAD9EC;" src="/install/log.txt" ></iframe>'
				});
				var nav = new Ext.Panel({
					title: '请输入配置信息',
					region: 'center',
					split: true,
					width: 500,
					bodyStyle:'background-color:#CAD9EC',
					plain: true,
					collapsible: false,
					margins:'3 0 3 3',
					cmargins:'13 3 3 3',
					items:simple
				});


			       //定义窗体
				   win = new Ext.Window({
						id:'win',
						iconCls:'key',
						title:'众盛科技-CMS-简易安装程序',
						layout:'border',	//自适应布局
						width:700,
						height:300,
                        bodyStyle:'padding:5px;',
						maximizable:false,//禁止最大化
						closeAction:'close',
						closable:false,//禁止关闭
						collapsible:true,//可折叠
						plain: true,
						buttonAlign:'center',
						items:[nav,log]//将表单作为窗体元素嵌套布局
					});

					win.on('show',function(){
                        //$('username').focus();
                        Ext.get('dbuser').focus();
                    }, this,{delay: 200});

					win.show();//显示窗体

                    //win.on('show',function(){TextField.focus()},this);
                    //$(document).ready(function(){
                    //  $("#username").focus();
                    //});




		 });
</script>
</body>
</html>
